package com.example.controller;

import com.example.entity.Host;
import com.example.entity.Order;
import com.example.entity.User;
import com.example.service.HostService;
import com.example.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;  // 订单服务
    @Autowired
    private HostService hostService;    // 寄养家庭服务


    @GetMapping("/create")
    public String showOrderForm(
            @RequestParam("family_id") Integer family_id,
            @RequestParam("service_type") String service_type,
            Model model,
            HttpSession session) {
        User user= (User) session.getAttribute("login_user");
        // 检查用户是否登录
        Integer userId = user.getUser_id();
        System.out.println("user"+user);
        if (userId == null) {
            return "redirect:/user/login";  // 未登录则重定向到登录页
        }

        // 获取寄养家庭信息
        Host host = hostService.getHostById(family_id);
        if (host == null) {
            return "redirect:/Hosts/list";  // 寄养家庭不存在则重定向到列表页
        }

        // 向视图添加属性
        model.addAttribute("familyId", family_id);
        model.addAttribute("serviceType", service_type);
        model.addAttribute("currentDate", new Date());
        model.addAttribute("host", host); // 添加寄养家庭信息

        return "order/create"; // 返回订单创建视图
    }


    @PostMapping("/create")
    public String createOrder(
            @ModelAttribute Order order,
            HttpSession session,
            Model model) {

        // 检查用户登录状态
        User user = (User) session.getAttribute("login_user");
        if (user == null) {
            return "redirect:/user/login";
        }

        // 设置订单请求者ID为当前登录用户
        order.setRequester_id(user.getUser_id());

        // 从寄养家庭获取服务提供者ID
        Host host = hostService.getHostById(order.getFamily_id());
        if (host == null) {
            model.addAttribute("error", "选择的寄养家庭不存在");
            return "order/create";
        }
        order.setProvider_id(host.getUser_id());

        // 设置初始订单状态
        order.setStatus("PENDING");

        // 计算订单价格（天数×每日价格）
        long days = (order.getEnd_date().getTime() - order.getStart_date().getTime()) / (24 * 60 * 60 * 1000) + 1;
        order.setPrice(new BigDecimal(host.getPrice() * days).setScale(2, BigDecimal.ROUND_HALF_UP));

        // 创建订单
        try {
            orderService.createOrder(order);
            return "redirect:/order/detail/" + order.getOrder_id();  // 创建成功重定向到详情页
        } catch (Exception e) {
            model.addAttribute("error", "订单创建失败: " + e.getMessage());
            return "order/create";  // 失败返回表单页显示错误
        }
    }


    @GetMapping("/detail/{order_id}")
    public String orderDetail(@PathVariable Integer order_id, Model model) {
        Order order = orderService.getOrderById(order_id);
        System.out.println("order"+order);
        model.addAttribute("order",order);
        if (order == null) {
            model.addAttribute("error", "订单不存在");
            return "error";  // 订单不存在返回错误页
        }

        model.addAttribute("order", order);
        return "order/detail";  // 返回订单详情视图
    }


    @GetMapping("/List")
    public String orderList(Model model, HttpSession session) {
        // 获取当前登录用户
        User user = (User) session.getAttribute("login_user");
        if (user == null) {
            return "redirect:/user/login";  // 未登录则重定向
        }

        // 根据用户角色获取不同的订单列表
        List<Order> orders;
        if ("PROVIDER".equals(user.getRole())) {
            // 服务提供者获取收到的订单
            orders = orderService.getOrdersByProviderId(user.getUser_id());
        } else {
            // 普通用户获取自己创建的订单
            orders = orderService.getOrdersByRequesterId(user.getUser_id());
        }

        model.addAttribute("orders", orders);
        return "/order/orderList";  // 返回订单列表视图
    }
}